//
//  ArticleTableViewCell.m
//  HYSmileiOS
//
//  Created by alekye on 16/4/24.
//  Copyright © 2016年 heyou. All rights reserved.
//

#import "ArticleTableViewCell.h"
#import "heyou.h"

/**
 *  提示按钮类型
 */
typedef NS_ENUM(NSInteger,TipButtonType) {
    /**
     *  播放GIF
     */
    TipButtonType_PlayGif = 1,
    /**
     *  下载重试
     */
    TipButtonType_Download_Retry,
};

/**
 *  下载失败类型
 */
typedef NS_ENUM(NSInteger, DownloadError) {
    /**
     *  无
     */
    DownloadError_None = 1,
    /**
     *  下载缩略图失败
     */
    DownloadError_ThumbImage,
    /**
     *  下载大图失败
     */
    DownloadError_FullImage,
};

@interface ArticleTableViewCell ()
// 下载进度条
@property (weak, nonatomic) ZFProgressView *progress;
// 播放按钮
@property (weak, nonatomic) UIButton *playButton;
// 数据模型
@property (weak, nonatomic) ArticleModel *articleModel;
// 下载错误类型
@property (assign, nonatomic) DownloadError downloadError;
@end

@implementation ArticleTableViewCell

- (void)awakeFromNib {
    // Initialization code
    // 创建加载进度条
    ZFProgressView *progress = [[ZFProgressView alloc] initWithFrame:CGRectMake(0, 0, 80, 80)];
    progress.backgroundStrokeColor = [UIColor lightGrayColor];
    progress.lineWidth = 4.0f;
    progress.GapWidth = 20.0f;
    [self.imageContent addSubview:progress];
    self.progress = progress;
    
    // 创建播放按钮
    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    button.backgroundColor = [UIColor whiteColor];
    button.frame = CGRectMake(0, 0, 30, 30);
    WS(ws);
    [button handleControlEvent:UIControlEventTouchUpInside withBlock:^(UIButton *sender) {
        ws.playButton.hidden = YES;
        TipButtonType buttonType = (TipButtonType)sender.tag;
        // 播放和下载重试功能共用一个按钮，需进行类型判断
        if (buttonType == TipButtonType_PlayGif) {
            if (ws.articleModel && ws.articleModel.type == HYImageType_GIF) {
                NSLog(@"imageURL = %@", ws.articleModel.imageUrl);
                [ws _playGif:ws.articleModel.imageUrl];
            }
        } else if (buttonType == TipButtonType_Download_Retry) {
            // 下载失败分两种情况，分别为：缩略图和大图
            if (ws.downloadError == DownloadError_ThumbImage) {
                [ws _downloadThumbImage:ws.articleModel.thumbnailUrl];
            } else if (ws.downloadError == DownloadError_FullImage) {
                [ws _downloadFullImage:ws.articleModel.imageUrl];
            }
        } else {
            NSAssert(NO, @"未知按钮类型");
        }
    }];
    [self.imageContent addSubview:button];
    self.playButton = button;
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

#pragma mark -- Play GIF
/**
 *  播放GIF图片
 *
 *  @param gifURL 图片地址
 */
- (void)_playGif:(NSString*)gifURL{
    NSString *fURL = gifURL;
    BOOL bExist = [[SDImageCache sharedImageCache] diskImageExistsWithKey:fURL];
    if (bExist) {
        // 本地已经缓存
        UIImage *tImage = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:fURL];
        // UIImage *tImage = [UIImage smc_imageFromColor:[HYTheme thumbImageColor] size:imageSize];
        self.imageContent.image = tImage;
    } else {
        // 需要网络下载
        [self _downloadFullImage:gifURL];
    }
}

/**
 *  显示错误的图片
 */
- (void)showErrorImage {
    CGFloat targetWidth = SCREEN_WIDTH - IMAGE_SPAN_LEFT - IMAGE_SPAN_RIGHT;    // 显示图片的ImageView宽度
    CGFloat targetHeight = targetWidth * IMAGE_MIN_RATIO_PNGJPG;
    self.layoutImageHeight.constant = targetHeight;
    UIImage *placeHolder = [UIImage smc_imageFromColor:[UIColor redColor] size:CGSizeMake(targetWidth, targetHeight)];   // 当你看到红色图片的时候，意味着这个图片出错了
    self.imageContent.image = placeHolder;
//    [self.imageContent showPlaceHolder];
}

/**
 *  根据图片的实际宽度获缩放后的高度
 *
 *  @param size 图片宽度大小
 *
 *  @return 等比缩放后的大小
 */
- (CGSize)getImageViewFitnessSize {
    ArticleModel *tm = self.articleModel;
    
    CGFloat realWidth = tm.thumbnailWidth;
    CGFloat realHeight = tm.thumbnailHeight;
    CGFloat targetWidth = SCREEN_WIDTH - IMAGE_SPAN_LEFT - IMAGE_SPAN_RIGHT;
    // 图片最小高度为 40.0f，否则autolayout适配会报错
    CGFloat targetHeight = IMAGE_MIN_HEIGHT;
    
    if (realWidth > 0) {
        CGFloat targetWidth = SCREEN_WIDTH - IMAGE_SPAN_LEFT - IMAGE_SPAN_RIGHT;
        targetHeight = realHeight / realWidth * targetWidth;
    } else {
        NSAssert(NO, @"图片宽度不能<0");
    }
    
    targetHeight = MAX(targetHeight, IMAGE_MIN_HEIGHT);
    
    return CGSizeMake(targetWidth, targetHeight);
}

/**
 *  将要显示缩略图，需要设置各种提示信息的位置和状态
 *
 *  @return 返回缩略图的大小
 */
- (void)_willShowThumbImage {
    CGSize imageSize = [self getImageViewFitnessSize];
    
    self.downloadError = DownloadError_None;
    
    // 设置ImageView的高度
    self.layoutImageHeight.constant = imageSize.height;
    
    // 设置位置
    CGPoint centerPoint = CGPointMake(imageSize.width/2.0f, imageSize.height/2.0f);
    self.progress.center = centerPoint;
    [self.progress setProgress:0.0f Animated:NO];
    self.playButton.center = centerPoint;
    
    // 由于Cell会被重用，这里需要设置各种控件的初始状态
    self.progress.hidden = YES;
    self.playButton.hidden = YES;
    
    self.downloadTipView.hidden = YES;  // 隐藏下载提示
    self.fullImageTip.hidden = YES;
    
}

/**
 *  缩略图已经显示完成
 */
- (void)_didShowThumbImage {
    self.downloadTipView.hidden = YES;  // 隐藏下载提示
    
    ArticleModel *tm = self.articleModel;
    if (tm.type == HYImageType_GIF) {
        // 显示播放提示
        [self _setTipButton:TipButtonType_PlayGif];
    } else {
        if ([tm hasFullImage]) {
            // 显示大图提示
            self.fullImageTip.hidden = NO;
        }
    }
}

/**
 *  大图显示完成（GIF）
 */
- (void)_didShowFullImage {
    self.downloadTipView.hidden = YES;  // 隐藏下载提示
}

/**
 *  下载失败
 */
- (void)_downloadImageError:(DownloadError)errorType {
    // 设置错误类型
    self.downloadError = errorType;
    // 显示重试按钮
    [self _setTipButton:TipButtonType_Download_Retry];
    // 显示下载错误提示信息
    [self _showDownloadTipView:YES];
}

///**
// *  下载大图错误
// */
//- (void)_downloadFullImageError {
//    self.downloadError = DownloadError_FullImage;
//    [self _setTipButton:TipButtonType_Download_Retry];
//    [self _showDownloadTipView:YES];
//}

/**
 *  设置按钮的提示类型
 */
- (void)_setTipButton:(TipButtonType)buttonType {
    self.playButton.hidden = NO;
    self.playButton.tag = buttonType;
    if (buttonType == TipButtonType_PlayGif) {
        [self.playButton setTitle:@"播" forState:UIControlStateNormal];
    } else if (buttonType == TipButtonType_Download_Retry) {
        [self.playButton setTitle:@"刷" forState:UIControlStateNormal];
    } else {
        NSAssert(NO, @"未知按钮类型");
    }
}

/**
 *  显示下载错误提示
 *
 *  @param animate 是否使用动画效果
 */
- (void)_showDownloadTipView:(BOOL)animate {
    self.downloadTipView.hidden = NO;
    if (animate) {
        WS(ws);
        ws.layoutDownTipViewHeight.constant = 0.0f;
        [ws.downloadTipView layoutIfNeeded];
//        [UIView animateWithDuration:0.3f animations:^{
//            ws.layoutDownTipViewHeight.constant = 40.0f;
//            [ws.downloadTipView layoutIfNeeded];
//        } completion:^(BOOL finished) {
//            
//        }];
        ws.downloadTipView.alpha = 0.0f;
        [UIView animateWithDuration:0.3f delay:0.0f options:UIViewAnimationOptionCurveLinear animations:^{
            ws.downloadTipView.alpha = 1.0f;
            ws.layoutDownTipViewHeight.constant = 40.0f;
            [ws.downloadTipView layoutIfNeeded];
        } completion:^(BOOL finished) {
            [ws.downloadTipView layoutIfNeeded];
        }];
    }
}

/**
 *  下载缩略图
 *
 *  @param thumbUrl 缩略图地址
 */
- (void)_downloadThumbImage:(NSString*)thumbUrl {
    // 显示下载进度条
    self.progress.hidden = NO;
    // 设置默认图片，开始下载
    CGSize imageSize = [self getImageViewFitnessSize];
    UIImage *placeHolder = [UIImage smc_imageFromColor:[HYTheme thumbImageColor] size:imageSize];
    NSURL *tURL = [NSURL URLWithString:thumbUrl];
    WS(ws);
    [self.imageContent sd_setImageWithURL:tURL placeholderImage:placeHolder options:SDWebImageRetryFailed progress:^(NSInteger receivedSize, NSInteger expectedSize) {
        // 更新下载进度
        if (expectedSize > 0) {
            CGFloat percent = (CGFloat)receivedSize / (CGFloat)expectedSize;
            [ws.progress setProgress:percent Animated:NO];
            NSLog(@"(%ld, %ld) - percent === %f", receivedSize, expectedSize, percent);
        }
    } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        NSLog(@"download thumb image ok");
        // 下载完成，隐藏下载进度条
        ws.progress.hidden = YES;
        if (error) {
            // 下载出错，显示点击重试按钮
            NSLog(@"---- complete ---- error = %@", error);
            [self _downloadImageError:DownloadError_ThumbImage];
        } else {
            // 下载成功
            [self _didShowThumbImage];
        }
    }];
}

/**
 *  下载大图
 *
 *  @param imageUrl 图片地址
 */
- (void)_downloadFullImage:(NSString*)imageUrl {
    // 显示下载进度条
    self.progress.hidden = NO;
    // 设置默认图片，开始下载
    UIImage *placeHolder = self.imageContent.image;
    NSURL *tURL = [NSURL URLWithString:imageUrl];
    WS(ws);
    [self.imageContent sd_setImageWithURL:tURL placeholderImage:placeHolder options:SDWebImageRetryFailed progress:^(NSInteger receivedSize, NSInteger expectedSize) {
        // 更新下载进度
        if (expectedSize > 0) {
            CGFloat percent = (CGFloat)receivedSize / (CGFloat)expectedSize;
            [ws.progress setProgress:percent Animated:NO];
            NSLog(@"(%ld, %ld) - percent === %f", receivedSize, expectedSize, percent);
        }
    } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        NSLog(@"download thumb image ok");
        // 下载完成，隐藏下载进度条
        ws.progress.hidden = YES;
        if (error) {
            // 下载出错，显示点击重试按钮
            NSLog(@"---- complete ---- error = %@", error);
            [self _downloadImageError:DownloadError_FullImage];
        } else {
            // 下载成功
            [self _didShowFullImage];
        }
    }];
}

/**
 *  设置图片信息，预期图片都需要填满UIImageView的宽度，高度自适应
 *
 *  @param model    数据模型
 *  @param download 设置是否需要下载图片，在TableViewCell用来计算高度的时候不需要下载
 */
- (void)setArticleInfo:(ArticleModel*)model  downloadImage:(BOOL)download{
    self.articleModel = model;
    ArticleModel *tm = model;
    self.labelDesc.text = tm.desc;

    [self _willShowThumbImage];
    NSString *fURL = model.thumbnailUrl;
    BOOL bExist = [[SDImageCache sharedImageCache] diskImageExistsWithKey:fURL];
    if (bExist) {
        // 本地已经缓存
        UIImage *tImage = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:fURL];
        self.imageContent.image = tImage;
        [self _didShowThumbImage];
    } else {
        // 需要网络下载
        if (download) {
            [self _downloadThumbImage:fURL];
        }
    }
    
}

/**
 *  根据图片类型获取可显示的最大高度
 *
 *  @param imageType 图片类型
 *
 *  @return 高度
 */
+ (CGFloat)getImageMaxVisibleHeight:(HYImageType)imageType {
    CGFloat height = 0.0f;
    CGFloat targetWidth = SCREEN_WIDTH - IMAGE_SPAN_LEFT - IMAGE_SPAN_RIGHT;    // 显示图片的ImageView宽度
    if (imageType == HYImageType_GIF) {
        height = targetWidth * IMAGE_MAX_RATIO_GIF;
    } else {
        height = targetWidth * IMAGE_MAX_RATIO_PNGJPG;
    }
    
    return height;
}

@end
